<template>
    <div>
        <el-upload ref="upload" v-model:file-list="fileList" :auto-upload="false" :limit="1" :on-exceed="handleExceed"
            :on-change="handleChange" list-type="picture">
            <el-button type="primary">点击上传</el-button>
            <template #tip>
                <div class="el-upload__tip">只能上传jpg/png文件，且不超过10Mb</div>
            </template>
        </el-upload>
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import * as http from '@/request/api'
import type {
    UploadInstance,
    UploadProps,
    UploadUserFile,
    UploadRawFile,
} from "element-plus";
import { ElMessage } from "element-plus";
const fileList = ref<UploadUserFile[]>([
    {
        name: "food.jpeg",
        url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
    },
]);

const upload = ref<UploadInstance>(); // 获取el-upload的DOM

// on-exceed：当超出个数限制时，执行的钩子函数
const handleExceed: UploadProps["onExceed"] = (files) => {
    upload.value!.clearFiles(); // clearFiles 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
    const file = files[0] as UploadRawFile; // 拿到最新上传的文件
    upload.value!.handleStart(file); // handleStart 手动选择文件
};

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const handleChange: UploadProps["onChange"] = async (
    uploadFile  
) => {
    const backupFileList = [...fileList.value]; // 备份已上传的文件，在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
    console.log(uploadFile);
    const { type, size } = uploadFile.raw as UploadRawFile;
    const validTypes = ["image/jpeg", "image/jpg", "image/png"];
    const maxSize = 10 * 1024 * 1024; // 单位byte
    if (!validTypes.includes(type) || size > maxSize) {
        ElMessage.error("只能上传jpg/png文件，且不超过10Mb!");
        fileList.value = backupFileList; // 在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
        return;
    }

    // 将文件通过接口给后端换取文件链接地址
    const formData = new FormData();
    formData.append("file", uploadFile.raw as UploadRawFile);
     http.minio.minioUpload(formData).then(res=>{
        console.log(res.name, res.url);
     })

};
</script> 